﻿using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Reactive.Linq;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using Serilog;
using SimpleTool.ActivityUnit.EchoControl;
using SimpleTool.Base;
using SimpleTool.Server;
using SimpleTool.TransformComponent;
using CommunityToolkit.Mvvm.Messaging;
using static SimpleTool.ActivityUnit.ActivitySectionModel;
using Microsoft.Win32;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Text.Json;
using Supabase.Postgrest.Attributes;
using Supabase.Postgrest.Models;
using System.Windows.Documents;
using Microsoft.Extensions.DependencyModel;
using DynamicData;
using DynamicData.Kernel;
using Serilog.Core;
using System;
using Microsoft.IdentityModel.Tokens;
using Supabase.Postgrest;


namespace SimpleTool.ActivityUnit
{
    public class ActivityViewModel : Notify
    {
        public readonly ILogger Logger = Log.ForContext<ActivityViewModel>();

        private readonly Stopwatch DBconnectWatch = Stopwatch.StartNew();

        private readonly int DBconnectTimeOut = 10000;

        public IPowerPlant PowerPlantServer;

        public IDatabaseServer DatabaseSeriver;

        public IDirFileServer DirFileServer;

        public IDenCryptoGraphic CryptoGraphic;

        private ActivitySectionModel? ActivitySectionModelStdin;

        private ActivityDetetor ActivityDetetor;

        private readonly DispatcherTimer DBTimer = new();

        private readonly ConditionalWeakTable<DispatcherTimer, ConnectFlag> ComplateKeyValuePairs = [];

        public Visibility CanViewChildKeyRegisterVisible
        {
            set
            {
                HoldActivitySectionModel.CanViewChildKeyRegisterVisible = value;
                propertyChangeSend(nameof(CanViewChildKeyRegisterVisible));
            }
            get
            {
                return HoldActivitySectionModel.CanViewChildKeyRegisterVisible;
            }
        }

        public string RegisterProductContent
        {
            set
            {
                HoldActivitySectionModel.RegisterProductContent = value;
                propertyChangeSend(nameof(RegisterProductContent));
            }
            get
            {
                return HoldActivitySectionModel.RegisterProductContent;
            }
        }

        public string RegisterProcessContent
        {
            set
            {
                HoldActivitySectionModel.RegisterProcessContent = value;
                propertyChangeSend(nameof(RegisterProcessContent));
            }
            get
            {
                return HoldActivitySectionModel.RegisterProcessContent;
            }
        }

        public string RunningStartContent
        {
            set
            {
                HoldActivitySectionModel.RunningStartContent = value;
                propertyChangeSend(nameof(RunningStartContent));
            }
            get
            {
                return HoldActivitySectionModel.RunningStartContent;
            }
        }

        public string RegisterProductHint 
        {
            set 
            {
                HoldActivitySectionModel.RegisterProductHint = value;
                propertyChangeSend(nameof(RegisterProductHint));
            } 
            get 
            {
                return HoldActivitySectionModel.RegisterProductHint;
            } 
        }

        public string RegisterProcessHint
        {
            set
            {
                HoldActivitySectionModel.RegisterProcessHint = value;
                propertyChangeSend(nameof(RegisterProcessHint));
            }
            get
            {
                return HoldActivitySectionModel.RegisterProcessHint;
            }
        }

        public string RegisterChildKeyHint
        {
            set
            {
                HoldActivitySectionModel.RegisterChildKeyHint = value;
                propertyChangeSend(nameof(RegisterChildKeyHint));
            }
            get
            {
                return HoldActivitySectionModel.RegisterChildKeyHint;
            }
        }

        public string RunningStartWorkOrder
        {
            set
            {
                HoldActivitySectionModel.RunningStartWorkOrder = value;
                propertyChangeSend(nameof(RunningStartWorkOrder));
            }
            get
            {
                return HoldActivitySectionModel.RunningStartWorkOrder;
            }
        }

        public string RunningStartImei
        {
            set
            {
                HoldActivitySectionModel.RunningStartImei = value;
                propertyChangeSend(nameof(RunningStartImei));
            }
            get
            {
                return HoldActivitySectionModel.RunningStartImei;
            }
        }

        public ObservableCollection<string> WorkOrdersTop { set; get; } = [];

        public ObservableCollection<string> ApplyImeisTop { set; get; } = [];

        public ObservableCollection<string> DynamicRichContent { set; get; } = [];

        public ObservableCollection<string> ProductSelectedValue { set; get; } = [];

        public ObservableCollection<string> ConfigurableSelectedValue { set; get; } = [];

        public ObservableCollection<SelectorContentStruct> ConfigurableSelectItems { set; get; } = [new SelectorContentStruct("\ue60c", "添加配置"),
                                                                                                    new SelectorContentStruct("\ue623", "编辑配置"),
                                                                                                    new SelectorContentStruct("\ue782", "保存配置"),
                                                                                                    new SelectorContentStruct("\ue645", "导入配置"),
                                                                                                    new SelectorContentStruct("\ue6bd", "回滚配置"),
                                                                                                    new SelectorContentStruct("\ue782", "退出配置")];

        public Dictionary<SelectorContentStruct, ObservableCollection<SelectorContentStruct>> ConfigurableSelectItemPair { set; get; } = [];

        public ObservableCollection<SelectorContentStruct> ProductSelectItems { set; get; } = [];

        public Dictionary<string, ObservableCollection<SelectorContentStruct>> ProductConfigPair { set; get; } = [];

        public Dictionary<SelectorContentStruct, ObservableCollection<SelectorContentStruct>> ProductSelectItemPair { set; get; } = [];

        public ObservableCollection<ActivityListBoxItemStruct> ActivityListItems { set; get; } = [];

        public ObservableCollection<MultilAtrributeStruct> ActivityEchoListItems { set; get; } = [];

        public List<MultilAtrributeStruct> ActivityBackEchoListItems { set; get; } = [];

        public object ControlContent
        {
            set
            {
                HoldActivitySectionModel.ControlContent = value;
                propertyChangeSend(nameof(ControlContent));
            }
            get
            {
                HoldActivitySectionModel.ControlContent ??= new ProductRichBoxUI();
                return HoldActivitySectionModel.ControlContent;
            }
        }

        public ActivityViewModel(IPowerPlant PowerServer, 
                                 IDatabaseServer databaseserver,
                                 IDenCryptoGraphic cryptoGraphicn,
                                 IDirFileServer dirFileServer)
        {
            PowerPlantServer = PowerServer;
            DatabaseSeriver = databaseserver;
            DirFileServer = dirFileServer;
            CryptoGraphic = cryptoGraphicn;
            ActivityDetetor = new ActivityDetetor(ReturnReceipt);
            DBTimer.Interval = new TimeSpan(50);

            ConnectFlag DBConnectFlag = ComplateKeyValuePairs.GetOrCreateValue(DBTimer);
            if (!DBConnectFlag.IsConnected)
            {
                WeakEventManager<DispatcherTimer, EventArgs>.AddHandler(DBTimer, nameof(DispatcherTimer.Tick), ReadyWork);
                DBConnectFlag.IsConnected = true;
                DBTimer.Start();
            }
            WeakReferenceMessenger.Default.Register<MvvmMessage>(this, MvvmMessageProcessPlant);
        }


        public ActivitySectionModel HoldActivitySectionModel
        {
            set
            {
                ActivitySectionModelStdin = value;
                propertyChangeSend(nameof(HoldActivitySectionModel));
            }
            get
            {
                ActivitySectionModelStdin ??= new ActivitySectionModel();
                return ActivitySectionModelStdin;
            }
        }

        public ICommand PrdTextChangeCommand
        {
            set
            {
                HoldActivitySectionModel.RegisterPrdStdin = value;
            }
            get
            {
                HoldActivitySectionModel.RegisterPrdStdin ??= new EasyCommand(PrdTextChangeEvent, bool () => { return true; });
                return HoldActivitySectionModel.RegisterPrdStdin;
            }
        }

        public ICommand DBReserveFileAddCommand
        {
            set
            {
                HoldActivitySectionModel.DBReserveFileAddStdin = value;
            }
            get
            {
                HoldActivitySectionModel.DBReserveFileAddStdin ??= new EasyCommand(DBReserveFileAddEvent, bool () => { return true; });
                return HoldActivitySectionModel.DBReserveFileAddStdin;
            }
        }

        public ICommand DBReserveFileSaveCommand
        {
            set
            {
                HoldActivitySectionModel.DBReserveFileSaveStdin = value;
            }
            get
            {
                HoldActivitySectionModel.DBReserveFileSaveStdin ??= new EasyCommand(DBReserveFileSaveEvent, bool () => { return true; });
                return HoldActivitySectionModel.DBReserveFileSaveStdin;
            }
        }

        public ICommand DBReserveFileExitStdin
        {
            set
            {
                HoldActivitySectionModel.DBReserveFileExitStdin = value;
            }
            get
            {
                HoldActivitySectionModel.DBReserveFileExitStdin ??= new EasyCommand(DBReserveFileExitEvent, bool () => { return true; });
                return HoldActivitySectionModel.DBReserveFileExitStdin;
            }
        }

        public ICommand PrsTextChangeCommand
        {
            set
            {
                HoldActivitySectionModel.RegisterPrsStdin = value;
            }
            get
            {
                HoldActivitySectionModel.RegisterPrsStdin ??= new EasyCommand(PrsTextChangeEvent, bool () => { return true; });
                return HoldActivitySectionModel.RegisterPrsStdin;
            }
        }

        public ICommand RegisterAcceptCommand
        {
            set
            {
                HoldActivitySectionModel.RegisterAcceptStdin = value;
            }
            get
            {
                HoldActivitySectionModel.RegisterAcceptStdin ??= new EasyCommand(RegisterAcceptEvent, bool () => { return true; });
                return HoldActivitySectionModel.RegisterAcceptStdin;
            }
        }

        public ICommand RegisterCancelCommand
        {
            set
            {
                HoldActivitySectionModel.RegisterCancelStdin = value;
            }
            get
            {
                HoldActivitySectionModel.RegisterCancelStdin ??= new EasyCommand(RegisterCancelEvent, bool () => { return true; });
                return HoldActivitySectionModel.RegisterCancelStdin;
            }
        }

        public ICommand RegisterChildKeyCommand
        {
            set
            {
                HoldActivitySectionModel.RegisterChildKeyStdin = value;
            }
            get
            {
                HoldActivitySectionModel.RegisterChildKeyStdin ??= new EasyCommand(RegisterChildKeyEvent, bool () => { return true; });
                return HoldActivitySectionModel.RegisterChildKeyStdin;
            }
        }
        
        public ICommand TestRunStartCommand
        {
            set
            {
                HoldActivitySectionModel.TestRunStartStdin = value;
            }
            get
            {
                HoldActivitySectionModel.TestRunStartStdin ??= new EasyCommand(TestStartChange, bool () => { return true; });
                return HoldActivitySectionModel.TestRunStartStdin;
            }
        }

        public ICommand OpenorConfigArgCommand
        {
            set
            {
                HoldActivitySectionModel.OpenorConfigArgStdin = value;
            }
            get
            {
                HoldActivitySectionModel.OpenorConfigArgStdin ??= new EasyCommand(OpenorConfigArgEvent, bool () => { return true; });
                return HoldActivitySectionModel.OpenorConfigArgStdin;
            }
        }

        public ICommand ConfigSelectionCommand
        {
            set
            {
                HoldActivitySectionModel.ConfigSelectionStdin = value;
            }
            get
            {
                HoldActivitySectionModel.ConfigSelectionStdin ??= new EasyCommand(ConfigurableChangeEvent, bool () => true);
                return HoldActivitySectionModel.ConfigSelectionStdin;
            }
        }

        public ICommand ProductSelectionCommand
        {
            set
            {
                HoldActivitySectionModel.ProductSelectionStdin = value;
            }
            get
            {
                HoldActivitySectionModel.ProductSelectionStdin ??= new EasyCommand(ProductChangeEvent, bool () => true);
                return HoldActivitySectionModel.ProductSelectionStdin;
            }
        }

        public static void MvvmMessageProcessPlant(object recipient, MvvmMessage message)
        {
            ActivityViewModel self = (ActivityViewModel)recipient;
            switch (message.Type)
            {
                case MvvmMessage.MvvmType.Product_ArrestInfoGroupOut:
                    self.EchoAttributeDisposeEvent(recipient, message);
                    break;

                case MvvmMessage.MvvmType.Database_ActivityStart:
                    self.DBconnectStart();
                    break;

                case MvvmMessage.MvvmType.Database_MapInfoGroup_Acquire:
                    self.EchoDBRelationDisposeEvent(recipient, message);
                    break;
            }
        }

        //开始测试
        public async void TestStartChange(object? param)
        {
            if (ActivityDetetor.State())
            {
                ActivityDetetor.Start(false);
                RecoverEctivityListItem();
            }
            else
            {
                if (PowerPlantServer.Action(2).Item1)
                {
                    await Task.Run(() =>
                    {
                        RecoverEctivityListItem();
                    });

                    ActivityDetetor.Start(true);
                    List<MultilAtrributeStruct> ApplyItems = [.. ActivityEchoListItems.Where(x => x.Status)];
                    await ActivityDetetor.ReadyRunning(ApplyItems);
                }
                else
                {
                    ReturnReceipt(new Check(MessageProPlantType.Message, "串口未打开"));
                }
            }
        }

        //重置测试项状态
        public void RecoverEctivityListItem()
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                int count = ActivityListItems.Count;
                for (int index = 0; index < count; index++)
                {
                    ActivityListItems[index] = new ActivityListBoxItemStruct(ActivityListItems[index].ActivityName, "MustardPop".FindSolidBrush());
                }
                propertyChangeSend(nameof(ActivityListItems));
            });
        }

        //添加数据库映射参考文件
        public async void DBReserveFileAddEvent(object? param)
        {
            OpenFileDialog FileSelector = new ()
            {
                DefaultDirectory = "dir".CurrentDir(),
                Filter = "Excel 文件 (*.xlsx)|*.xlsx",
                Multiselect = true
            };

            if (FileSelector.ShowDialog() is not null and bool)
            {
                List<string> consultColumns = await GetConsultWorkOrderField([.. FileSelector.FileNames]);

                GetDBfieldMapInfos(consultColumns);
            }
        }

        //添加数据库映射参考列
        public async Task<List<string>> GetConsultWorkOrderField(List<string> CusultWorkOrders)
        {
            List<string> CusultColumnNames = [];
            await Task.Run(async () =>
            {
                foreach (var file in CusultWorkOrders)
                {
                    var sheets = await DirFileServer.GetExcel(new ExcelOptions(file));

                    foreach (var sheet in sheets)
                    {
                        CusultColumnNames.AddRange(sheet.Value.Keys);
                    }
                }
            });
            return CusultColumnNames;
        }

        //字段映射保存
        public void DBReserveFileSaveEvent(object? param)
        {
            WeakReferenceMessenger.Default.Send<MvvmMessage>(new MvvmMessage(MvvmMessage.MvvmType.Database_MapInfoGroup_Request));
        }

        //退出字段映射
        public void DBReserveFileExitEvent(object? param)
        {
            _ = Task.Run(() =>
            {
                Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    ProductRichBoxUI UI = new();
                    ControlContent = UI;
                    propertyChangeSend(nameof(DynamicRichContent));
                }, DispatcherPriority.Background);
            });
        }

        //注册子键 / 主键 切换
        public void RegisterChildKeyEvent(object? param)
        {
            if (param is not null)
            {
                HoldActivitySectionModel.RegisterIsSecondaryKey = int.Parse(param.GetSafetyChar());
                switch (HoldActivitySectionModel.RegisterIsSecondaryKey)
                {
                    case 1:
                        CanViewChildKeyRegisterVisible = Visibility.Visible;
                        RegisterProductHint = "关联主键";
                        RegisterProcessHint = "子键名称";
                        break;

                    case 0:
                        CanViewChildKeyRegisterVisible = Visibility.Collapsed;
                        RegisterProductHint = "主键名称";
                        break;
                }
            }
        }

        //获取注册产品名称
        public void PrdTextChangeEvent(object? param)
        {
            if (param is not null)
            {
                RegisterProductContent = param.GetSafetyChar();
            }
        }

        //获取注册产工序
        public void PrsTextChangeEvent(object? param)
        {
            if (param is not null)
            {
                RegisterProcessContent = param.GetSafetyChar();
            }
        }
        
        //配置选项选择
        public void ConfigurableChangeEvent(object? param)
        {
            Application.Current.Dispatcher.Invoke(async () =>
            {
                if (param is not null and List<string> selects && selects.Count >= 1)
                {
                    int sendTimeout = 7000;
                    Stopwatch stopwatch = Stopwatch.StartNew();
                    string key = selects[0];
                    switch (key)
                    {
                        case "添加配置":
                            if (ControlContent is ProductConfigUI _ConfigUIAdd && _ConfigUIAdd.IsVisible)
                            {
                                WeakReferenceMessenger.Default.Send<MvvmMessage>(new MvvmMessage(MvvmMessage.MvvmType.Product_StepAddtion));
                            }
                            break;

                        case "编辑配置":
                            
                            if (HoldActivitySectionModel.ControlContent is not (not null and ProductConfigUI))
                            {

                                _ = Task.Run(() =>
                                {
                                    Application.Current.Dispatcher.InvokeAsync(() =>
                                    {
                                        ProductConfigUI UI = new();
                                        ControlContent = UI;
                                    }, DispatcherPriority.Background);
                                });

                                while (true)
                                {
                                    if (ActivityEchoListItems.Count > 0 && ControlContent is ProductConfigUI _ConfigUIEdit && _ConfigUIEdit.IsVisible)
                                    {
                                        WeakReferenceMessenger.Default.Send<MvvmMessage>(new MvvmMessage(MvvmMessage.MvvmType.Product_StepSend, ActivityEchoListItems));
                                        break;
                                    }
                                    if (stopwatch.ElapsedMilliseconds > sendTimeout)
                                    {
                                        stopwatch.Stop();
                                        stopwatch.Restart();
                                        break;
                                    } 
                                    else if (!stopwatch.IsRunning)
                                    {
                                        break;
                                    }
                                    await Task.Delay(200);
                                }
                            }
                            break;

                        case "保存配置":
                            stopwatch.Stop();
                            stopwatch.Restart();
                            if (ControlContent is ProductConfigUI _ConfigUISave && _ConfigUISave.IsVisible)
                            {
                                WeakReferenceMessenger.Default.Send<MvvmMessage>(new MvvmMessage(MvvmMessage.MvvmType.Product_ArrestInfoGroupSet));
                            }
                            break;

                        case "退出配置":
                            stopwatch.Stop();
                            stopwatch.Restart();
                            if (ControlContent is ProductConfigUI _ConfigUIExit && _ConfigUIExit.IsVisible)
                            {
                                _= Task.Run(() =>
                                {
                                    Application.Current.Dispatcher.InvokeAsync(() =>
                                    {
                                        ProductRichBoxUI UI = new();
                                        ControlContent = UI;
                                        propertyChangeSend(nameof(DynamicRichContent));
                                    }, DispatcherPriority.Background);
                                });
                            }
                            break;

                        case "回滚配置":
                            EchoAttributeDisposeEvent(this, new MvvmMessage(MvvmMessage.MvvmType.Product_ArrestInfoGroupSet, ActivityBackEchoListItems));
                            break;

                        case "导入配置":
                            Logger.DebudElite(ProductSelectedValue.Join(" · "));
                            break;
                    }
                }
            });
        }

        //产品工序选择
        public async void ProductChangeEvent(object? param)
        {
            await Application.Current.Dispatcher.Invoke(async () =>
            {
                if (param is not null and List<string> selects && selects.Count >= 1)
                {
                    List<string> DuplicateList = [.. selects];
                    bool isTreeChild = selects.Count >= 2 && !string.IsNullOrEmpty(DuplicateList[0]) && !string.IsNullOrEmpty(DuplicateList[1]);
                    string key = selects[0];
                    if (key == "产品管理")
                    {
                        _= Task.Run(() =>
                        {
                            Application.Current.Dispatcher.InvokeAsync(() =>
                            {
                                ProductRegisterUI UI = new();
                                ControlContent = UI;
                            }, DispatcherPriority.Background);
                        });
                    }
                    
                    else if (key == "预置数据库" && isTreeChild)
                    {
                        string function = selects[1];
                        switch (function)
                        {
                            case "工单添加":
                                WorkOrderImport();
                                break;

                            case "字段映射":

                                _ = Task.Run(() =>
                                {
                                    Application.Current.Dispatcher.InvokeAsync(() =>
                                    {
                                        ReserveDutyMapUI UI = new();
                                        ControlContent = UI;

                                        KeyValuePair<Dictionary<string, string>, List<string>> infoGrounp = new (
                                            HoldActivitySectionModel.DBWorkOrderMap,
                                            HoldActivitySectionModel.CusultColumnNames);

                                        WeakReferenceMessenger.Default.Send<MvvmMessage>(new MvvmMessage(MvvmMessage.MvvmType.Database_MapFilesSend, infoGrounp));

                                    }, DispatcherPriority.Background);
                                });
                                break;
                        }
                    }
                    
                    else
                    {
                        if (isTreeChild)
                        {
                            string product = DuplicateList[0];
                            string process = DuplicateList[1];
                            Logger.DebudElite(product, process);
                            if (!ActivityAssistBehivor.Behivor.ProductFixedOpptions.Any(x => product.Contains(x)))
                            {
                                HoldActivitySectionModel.ProductSelectedValue = DuplicateList;
                                GetDBfieldMapInfos();
                            }
                            if (DatabaseSeriver.GetIdentify())
                            {
                                if (DatabaseSeriver.GetCloudDB() is not null and Supabase.Client CloudDB)
                                {
                                    await CloudDB.From<ProductConfigRelation>()
                                                 .Where(x => x.PrdId != null && x.PrdId != "")
                                                 .Set(x => x.PrdApply, 0).Update();

                                    await CloudDB.From<ProductConfigRelation>()
                                                 .Where(x => x.PrdName == product && x.PrdProcess == process)
                                                 .Set(x => x.PrdApply, 1).Update();
                                }
                            }
                            else
                            {
                                await DatabaseSeriver.LocalDBQueryFree($"UPDATE product_config_relation SET prd_apply={0}",
                                                                       $"UPDATE product_config_relation SET prd_apply={1} WHERE " +
                                                                       $"prd_name='{DuplicateList[0]}' and prd_process='{DuplicateList[1]}'");
                            }
                            await GetConfigInfos(DuplicateList[0], DuplicateList[1]);
                        }
                    }

                    if (key.Contains("和易充"))
                    {
                        ActivityDetetor.SetMainAccording("HYC");
                    }
                }
            });
        }

        //工单导入
        public async void WorkOrderImport()
        {
            if (HoldActivitySectionModel.DBWorkOrderMap.Keys.Select(x => !string.IsNullOrEmpty(x)).Count() == 0)
            {
                CustomMessageBox.Show("提示", 0, ["知道了"], "不存在映射数据，请选择数据库-字段映射，添加映射数据");
                return;
            }

            OpenFileDialog FileSelector = new OpenFileDialog()
            {
                DefaultDirectory = "dir".CurrentDir(),
                Filter = "Excel 文件 (*.xlsx)|*.xlsx",
                Multiselect = true
            };

            bool? diaLogShow = FileSelector.ShowDialog();

            string[] getFiles = FileSelector.FileNames;
            List<string> Workorders = [];
            await Task.Run(() =>
            {
                foreach (var file in getFiles)
                {
                    Workorders.Add(Regex.Split(DirFileServer.GetSimpleName(file),
                        "[\\W_]+").Where(x => !string.IsNullOrEmpty(Regex.Match(x, "\\d+").Value)).Last());
                }
            });

            bool RunningToken = true;

            // 已有工单的处理
            if (DatabaseSeriver.GetIdentify())
            {
                if (DatabaseSeriver.GetCloudDB() is not null and Supabase.Client CloudDB)
                {
                    var queryResult = await CloudDB.From<WorkOrderPreview>().Filter("workorder_num", Supabase.Postgrest.Constants.Operator.In, Workorders).Get();

                    if (queryResult.Model is not null)
                    {

                        var question = CustomMessageBox.Show("提示", 0, ["取消导入", "覆盖导入"], "已存在工单，是否覆盖");

                        if (question.index == 1)
                        {
                            await CloudDB.From<WorkOrderPreview>().Filter("workorder_num", Supabase.Postgrest.Constants.Operator.In, Workorders).Delete();
                        }
                        else
                        {
                            RunningToken = false;
                        }
                    }
                }
            }
            
            else
            {
                string combination = Workorders.Join(",", true);

                if (DatabaseSeriver.LocalDBSurvival(DBreserveInfo.LocalDBName))
                {
                    var queryResult = await DatabaseSeriver.LocalDBQueryFree($"SELECT * FROM workorder_preview WHERE workorder_num in ({combination})");

                    if (queryResult.Result.Count > 0)
                    {
                        var question = CustomMessageBox.Show("提示", 0, ["取消导入", "覆盖导入"], "已存在工单，是否覆盖");

                        if (question.index == 1)
                        {
                            await DatabaseSeriver.LocalDBQueryFree($"DELETE * FROM WHERE workorder_preview wkod_num in ({combination})");
                        }
                        else
                        {
                            RunningToken = false;
                        }
                    }
                }
            }

            if (diaLogShow is not null and bool && RunningToken)
            {
                await Task.Run(async () =>
                {
                    foreach (var file in FileSelector.FileNames)
                    {
                        var callback = CustomMessageBox.Show(0, 100);

                        var sheets = await DirFileServer.GetExcel(new ExcelOptions(file)
                        {
                            questionSheet = true,
                            HintCallBack = (sheet, column, prograss) =>
                            {
                                callback.Invoke(prograss, $"工作簿: {sheet}  列: {column} 读取中...");
                            }
                        }, ExcelOriented.RowOriented);

                        ICollection<WorkOrderUnfold> CloudSqlUnfoldDatas = []; //cloud datas

                        ICollection<WorkOrderPreview> CloudSqlPreviewDatas = []; //cloud datas

                        List<string> LocalUnfoldSql = [];

                        List<string> LocalPreviewSql = [];

                        List<string> LocalUnfoldSqlDatas = []; // local datas

                        List<string> LocalPreviewSqlDatas = []; // local datas

                        void DependencyAppend<T>(ICollection<T> values, List<string> dependencys, Dictionary<string, List<string>> difference)
                        {

                            int index = 0;
                            foreach (var property in values)
                            {
                                foreach (var depedency in dependencys)
                                {
                                    (string, string, List<string>)? differences = difference[depedency].GetDifference<string>();
                                    DependencyDBPropertyType DependencyType = ActivityAssistBehivor.Behivor.DBDependencyMap[depedency].Value;
                                    if (property is not null && differences is not null &&
                                        property.GetProperty(depedency) is not null and PropertyInfo depedencyInfo)
                                    {
                                        switch (DependencyType)
                                        {
                                            case DependencyDBPropertyType.difference:
                                                depedencyInfo.SetValue(property, differences.Value.Item3[index]);
                                                break;
                                            case DependencyDBPropertyType.start:
                                                depedencyInfo.SetValue(property, differences.Value.Item1);
                                                break;
                                            case DependencyDBPropertyType.end:
                                                depedencyInfo.SetValue(property, differences.Value.Item2);
                                                break;
                                        }
                                    }
                                }
                                index++;
                            }
                        }

                        (List<string>, Dictionary<string, List<string>>) GetDifference() // 获取差异字典所需数据
                        {
                            List<string> dependencys = [.. ActivityAssistBehivor.Behivor.DBDependencyMap.Keys];

                            Dictionary<string, List<string>> difference = [];

                            if (ActivityAssistBehivor.Behivor.DBDependencyMap.Keys.Count > 0)
                            {
                                foreach (var unfold in CloudSqlUnfoldDatas)
                                {
                                    foreach (var depedency in dependencys)
                                    {
                                        string previorKey = ActivityAssistBehivor.Behivor.DBDependencyMap[depedency].Key;
                                        
                                        if (unfold.GetProperty(previorKey) is not null and PropertyInfo property && 
                                            property.GetValue(unfold) is not null and object value)
                                        {
                                            if (difference.TryGetValue(depedency, out List<string>? values))
                                            {
                                                values.Add(value.GetSafetyChar());
                                            }
                                            else
                                            {
                                                difference.Add(depedency, [value.GetSafetyChar()]);
                                            }
                                        }
                                    }
                                }
                            }
                            return (dependencys, difference);
                        }

                        void LocalAppend<T>(ICollection<T> values, List<string> dependencys, Dictionary<string, List<string>> difference)
                        {
                            int index = 0;
                            foreach (var value in values)
                            {
                                List<string> propertyNames = [];
                                List<string> propertyValues = [];
                                if (value is not null)
                                {
                                    
                                    foreach (PropertyInfo property in value.GetPropertys())
                                    {
                                        ColumnAttribute? attribute = property.GetCustomAttribute<ColumnAttribute>();
                                        if (attribute is not null)
                                        {
                                            string? _key = attribute.ColumnName;
                                            string? _value = property.GetValue(value)?.GetSafetyChar();
                                            
                                            if (!string.IsNullOrEmpty(_value) && !string.IsNullOrEmpty(_key))
                                            {
                                                propertyNames.Add(_key);
                                                propertyValues.Add(_value);
                                            }
                                        }
                                    }

                                    string propertyType = typeof(T).Name;
                                    switch (propertyType)
                                    {
                                        case nameof(WorkOrderUnfold):
                                            LocalUnfoldSql.Add($"INSERT INTO workorder_unfold({propertyNames.Join(",")}) " +
                                                                $"VALUES({propertyValues.Join(",", true)})");

                                            break;
                                        case nameof(WorkOrderPreview):
                                            LocalPreviewSql.Add($"INSERT INTO workorder_preview({propertyNames.Join(",")}) " +
                                                                $"VALUES({propertyValues.Join(",", true)})");

                                            break;
                                    }
                                }
                                index++;
                                
                            }
                        }

                        foreach (var sheet in sheets) // looping all sheet
                        {

                            Dictionary<string, List<string>> sheet_value = sheet.Value; // all row datas

                            List<string> FieldMap = [];

                            foreach (var section in sheet_value)
                            {
                                if (section.Key == "Title")
                                {
                                    FieldMap = section.Value; // first row data , map translation
                                }
                                else
                                {
                                    int column_index = 0;

                                    List<string> row_values = section.Value;

                                    WorkOrderUnfold orderUnfold = new();
                                    
                                    WorkOrderPreview orderPreview = new();

                                    List<PropertyInfo> UnfoldPropertys = orderUnfold.GetPropertys(2);
                                    
                                    List<PropertyInfo> PreviewPropertys = orderPreview.GetPropertys(2);

                                    foreach (var value in row_values)
                                    {
                                        string column_name = FieldMap[column_index]; // 列名
                                        string? realKey = HoldActivitySectionModel.DBWorkOrderMap.GetSafetyKey<string, string>(column_name); //对应映射字段
                                        if (realKey is not null)
                                        {
                                            var findUnfoldProperty = UnfoldPropertys.Where(x => x.Name == realKey);
                                            if (findUnfoldProperty.Any() && findUnfoldProperty.ElementAt(0).CanSafetyConvert(value, out object? _value1))
                                            {
                                                findUnfoldProperty.ElementAt(0).SetValue(orderUnfold, _value1);
                                            }

                                            var findPreviewProperty = PreviewPropertys.Where(x => x.Name == realKey);
                                            if (findPreviewProperty.Any() && findPreviewProperty.ElementAt(0).CanSafetyConvert(value, out object? _value2))
                                            {
                                                findPreviewProperty.ElementAt(0).SetValue(orderPreview, _value2);
                                            }
                                        }
                                        column_index++;
                                    }
                                    // 添加单行数据，限制统计表导入条件
                                    CloudSqlUnfoldDatas.Add(orderUnfold);
                                    if (!CloudSqlPreviewDatas.Any(x => x.WorkorderNum == orderPreview.WorkorderNum))
                                    {
                                        CloudSqlPreviewDatas.Add(orderPreview);
                                    }
                                }
                            }
                            try
                            {
                                var Difference = GetDifference();
                                var dependencys = Difference.Item1;
                                var difference = Difference.Item2;

                                DependencyAppend<WorkOrderUnfold>(CloudSqlUnfoldDatas, dependencys, difference);

                                DependencyAppend<WorkOrderPreview>(CloudSqlPreviewDatas, dependencys, difference);

                                if (DatabaseSeriver.GetIdentify())
                                {
                                    if (DatabaseSeriver.GetCloudDB() is not null and Supabase.Client CloudDB)
                                    {
                                        await CloudDB.From<WorkOrderUnfold>().Insert(CloudSqlUnfoldDatas);

                                        await CloudDB.From<WorkOrderPreview>().Insert(CloudSqlPreviewDatas);
                                    }
                                }
                                else
                                {

                                    if (DatabaseSeriver.LocalDBSurvival(DBreserveInfo.LocalDBName))
                                    {
                                        LocalAppend<WorkOrderUnfold>(CloudSqlUnfoldDatas, dependencys, difference);

                                        LocalAppend<WorkOrderPreview>(CloudSqlPreviewDatas, dependencys, difference);
                                    }

                                    await DatabaseSeriver.LocalDBQuery(LocalUnfoldSql);
                                    await DatabaseSeriver.LocalDBQuery(LocalPreviewSql);
                                }
                            }
                            catch (Exception error)
                            {
                                CustomMessageBox.Show("警告", 1, ["知道了"], error.Message);
                            }
                        }
                    }
                });
            }
        }

        //注册产品和工序
        public void RegisterCancelEvent(object? param)
        {

            _ = Task.Run(() =>
            {
                Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    ProductRichBoxUI UI = new();
                    ControlContent = UI;
                    propertyChangeSend(nameof(DynamicRichContent));
                }, DispatcherPriority.Background);
            });
        }

        //产品、工序注册
        public async void RegisterAcceptEvent(object? param)
        {
            bool baseVerify(List<object> products, List<object> processs)
            {

                if (string.IsNullOrEmpty(RegisterProductContent))
                {
                    RegisterChildKeyHint = "主键不可为空";
                }
                else if (HoldActivitySectionModel.RegisterIsSecondaryKey == 1 && string.IsNullOrEmpty(RegisterProcessContent))
                {
                    RegisterChildKeyHint = "子键不可为空";
                }

                //检查主键索引
                if (products.Contains(RegisterProductContent))
                {
                    //操作为添加子键时，检查子键是否存在
                    if (HoldActivitySectionModel.RegisterIsSecondaryKey == 1)
                    {
                        int index = 0;
                        bool state = true;
                        foreach (var prd in products)
                        {
                            if (prd.Equals(RegisterProductContent.Trim()))
                            {
                                if (processs.Contains(RegisterProcessContent) &&
                                    products.IndexOf(index) == processs.IndexOf(index))
                                {
                                    state = false;
                                    RegisterChildKeyHint = "子键已存在";
                                    break;
                                }
                            }
                            index++;
                        }
                        return state;
                    }
                    else
                    {
                        bool state = true;
                        int index = 0;
                        foreach (var prd in products)
                        {
                            if (prd.Equals(RegisterProductContent.Trim()))
                            {
                                if (string.IsNullOrEmpty(processs[index].GetSafetyChar()))
                                {
                                    RegisterChildKeyHint = "主键已存在";
                                    state = false;
                                    break;
                                }
                            }
                            index++;
                        }
                        return state;
                    }
                }
                else
                {
                    return true;
                }
            }

            try
            {
                if (DatabaseSeriver.GetIdentify())
                {
                    if (DatabaseSeriver.GetCloudDB() is not null and Supabase.Client CloudDB)
                    {
                        var queryResult = await CloudDB.From<ProductConfigRelation>()
                            .Get();

                        List<object> ids = [.. queryResult.Models.Select(x => (object)x.PrdId)];
                        List<object> products = [.. queryResult.Models.Select(x => (object)x.PrdName)];
                        List<object> processs = [.. queryResult.Models.Select(x => (object)x.PrdProcess)];
                        bool canExecbute = baseVerify(products, processs);
                        Logger.DebudElite("结果0: ", canExecbute);
                        if (canExecbute)
                        {
                            string idkey = ids.GetDesorderly();
                            ProductConfigRelation insertData = new()
                            {
                                PrdId = idkey,
                                PrdName = RegisterProductContent,
                                PrdProcess = RegisterProcessContent,
                                PrdTreeKey = HoldActivitySectionModel.RegisterIsSecondaryKey,
                                PrdApply = 0
                            };

                            var InsertResponse = await CloudDB.From<ProductConfigRelation>().Insert(insertData);

                            if (InsertResponse.ResponseMessage is not null && 
                                InsertResponse.ResponseMessage.IsSuccessStatusCode)
                            {
                                RegisterChildKeyHint = "键值添加成功";
                                GetProductInfos();
                                Logger.DebudElite($"info write to sql success, where prd {RegisterProductContent}");
                            }
                        }
                    }
                }
                else
                {
                    async void insertSqlExecute(string idkey)
                    {
                        string insertCommandSql = $"INSERT INTO product_config_relation VALUES(" +
                                                  $"'{idkey}'," +
                                                  $"'{RegisterProductContent}'," +
                                                  $"'{RegisterProcessContent}'," +
                                                  $"{HoldActivitySectionModel.RegisterIsSecondaryKey}," +
                                                  $"{0})";

                        if (!string.IsNullOrEmpty(insertCommandSql) && await DatabaseSeriver.LocalDBQueryFree(insertCommandSql) != null)
                        {
                            RegisterChildKeyHint = "键值添加成功";
                            Logger.DebudElite($"info write to sql success, where prd {RegisterProductContent}");
                        }
                    }

                    string queryCommandSql = $"SELECT * FROM product_config_relation";
                    if (await DatabaseSeriver.LocalDBQueryFree(queryCommandSql) is var queryResult && queryResult.ErrorHint == null)
                    {
                        if (queryResult.ErrorHint == null &&
                            queryResult.Result.TryGetValue(queryCommandSql, out Dictionary<string, List<object>>? dataDict) &&
                            dataDict.TryGetValue("prd_id", out List<object>? ids) &&
                            dataDict.TryGetValue("prd_name", out List<object>? products) &&
                            dataDict.TryGetValue("prd_name", out List<object>? processs))
                        {
                            bool canExecbute = baseVerify(products, processs);
                            string idkey = ids.GetDesorderly();

                            if (canExecbute) insertSqlExecute(idkey);
                        }
                        else
                        {
                            string idkey = 2.GetDesorderly();
                            insertSqlExecute(idkey);
                        }
                        
                    }
                }
               
                _ = Task.Delay(1400).ContinueWith((task) =>
                {
                    RegisterChildKeyHint = "是否子键";
                });
            } catch (Exception error)
            {
                Logger.DebudElite($"register product encount error: {error.Message}");
            }
        }

        //获取配置信息
        public async Task GetConfigInfos(string product, string process)
        {
            void GetActivityListItem()
            {
                try
                {
                    ActivityEchoListItems = [.. ActivityEchoListItems.OrderBy(x => x.Priority)];

                    List<ActivityListBoxItemStruct> PriorityItemsStruct = [];
                    foreach (var item in ActivityEchoListItems.Where(x => x.Status))
                    {
                        PriorityItemsStruct.Add(new ActivityListBoxItemStruct(item.Step, "MustardPop".FindSolidBrush()));
                    }
                    ActivityListItems = [.. PriorityItemsStruct];
                }
                catch (Exception error)
                {
                    Logger.DebudElite($"Priority collection from configural: {error.Message}");
                }
            }

            if (DatabaseSeriver.GetIdentify())
            {
                if (DatabaseSeriver.GetCloudDB() is not null and Supabase.Client CloudDB)
                {
                    string code = CryptoGraphic.ENbase64(product + process);

                    var queryResult = await CloudDB.From<ProductConfigField>()
                        .Where(x=>x.Code == code)
                        .Get();

                    Logger.ErrorElite(code, queryResult.Models.Count);

                    if (queryResult.Models.Count == 1 && queryResult.Model is not null)
                    {
                        List<MultilAtrributeStruct>? DejsonCollection = JsonSerializer.Deserialize<List<MultilAtrributeStruct>>(
                                                     queryResult.Model.FieldJson, HoldActivitySectionModel.JsonOptions);
                        if (DejsonCollection is not null)
                        {
                            ActivityEchoListItems = [.. DejsonCollection];
                        }
                        Logger.DebudElite(CryptoGraphic.ENbase64(product + process));
                        GetActivityListItem();
                    }
                    else
                    {
                        if (queryResult.Models.Count == 0)
                        {
                            ActivityEchoListItems = [];
                            ActivityListItems = [];
                        }
                        else if (queryResult.Models.Count > 1)
                        {
                            CustomMessageBox.Show("警告", 1, ["知道了"], $"存在{queryResult.Models.Count}条数据");
                        }
                    }
                }
            }
            else
            {
                if (DatabaseSeriver.LocalDBSurvival(DBreserveInfo.LocalDBName))
                {
                    string queryConfigSql = $"SELECT * FROM product_config_field WHERE field_product='{product}' and field_process='{process}'";
                    if (await DatabaseSeriver.LocalDBQueryFree(queryConfigSql) is var queryResult &&
                        queryResult.ErrorHint == null &&
                        queryResult.Result.TryGetValue(queryConfigSql, out Dictionary<string, List<object>>? ConfigDict))
                    {
                        if (ConfigDict is not null &&
                            ConfigDict.Count > 0 &&
                            ConfigDict.TryGetValue("field_json", out List<object>? fieldJson))
                        {
                            await Task.Run(() =>
                            {
                                if (fieldJson.Count == 1)
                                {
                                    List<MultilAtrributeStruct>? DejsonCollection = JsonSerializer.Deserialize<List<MultilAtrributeStruct>>(
                                        fieldJson[0].GetSafetyChar(), HoldActivitySectionModel.JsonOptions);
                                    if (DejsonCollection is not null)
                                    {
                                        ActivityEchoListItems = [.. DejsonCollection];
                                    }

                                    GetActivityListItem();
                                }
                                else
                                {
                                    if (fieldJson.Count == 0)
                                    {
                                        ActivityEchoListItems = [];
                                        ActivityListItems = [];
                                    }
                                    else if (fieldJson.Count > 1)
                                    {
                                        CustomMessageBox.Show("警告", 1, ["知道了"], $"存在{fieldJson.Count}条数据");
                                    }
                                }
                            });
                        }
                        else
                        {
                            ActivityEchoListItems = [];
                            ActivityListItems = [];
                        }
                    }
                    else
                    {
                        ActivityEchoListItems = [];
                        ActivityListItems = [];
                    }
                }
            }
            propertyChangeSend(nameof(ActivityListItems));
        }

        //获取产品和工序
        public async void GetProductInfos()
        {
            try
            {
                await Application.Current.Dispatcher.Invoke(async () =>
                {
                    ProductSelectItems.Clear();
                    ObservableCollection<string> EchoSelectValue = [];
                    Dictionary<string, List<string>> pairClassify = [];

                    SelectorContentStruct ProductManager = new ("\ue615", "产品管理", "BurgundyNight".FindSolidBrush());
                    SelectorContentStruct ReserveDutyDB = new("\ue616", "预置数据库", "BurgundyNight".FindSolidBrush())
                    {
                        Visibility = Visibility.Visible
                    };
                    SelectorContentStruct ReserveDutyDBAdd = new("\ue602", "工单添加", "BurgundyNight".FindSolidBrush());
                    SelectorContentStruct ReserveDutyDBView = new("\ue631", "工单预览", "BurgundyNight".FindSolidBrush());
                    SelectorContentStruct ReserveDutyDBMap = new("\ue68e", "字段映射", "BurgundyNight".FindSolidBrush());

                    ObservableCollection<SelectorContentStruct> ReserveDutyChilds = [ReserveDutyDBAdd, ReserveDutyDBView, ReserveDutyDBMap];

                    ProductSelectItems.Add(ProductManager);
                    ProductSelectItems.Add(ReserveDutyDB);
                    
                    // 添加工序数据
                    void LoaderData(string product, string process, int treekey, int apply)
                    {
                        if (treekey == 0) // 产品名称项直接添加
                        {
                            ProductSelectItems.Add(new SelectorContentStruct("\ue691", product));
                        }
                        else // 带有子项的则做好分类，即所属产品 - 包含工序
                        {
                            if (pairClassify.TryGetValue(product, out List<string>? values) && values is not null)
                            {
                                pairClassify[product].Add(process);
                            }
                            else
                            {
                                pairClassify[product] = [process];
                            }
                        }

                        if (apply == 1 && treekey == 1) // 获取包含子项的已应用数据
                        {
                            EchoSelectValue.Add(product);
                            if (!string.IsNullOrEmpty(process)) EchoSelectValue.Add(process);
                        }
                    }

                    async void GetConfigInfo(List<object> products, List<object> processs)
                    {
                        // 没有应用项或者不存在子项时，默认显示第一条数据
                        if (EchoSelectValue.Count == 0 && products.Count > 0 && products.Count > 0)
                        {
                            EchoSelectValue.Add(products[0].GetSafetyChar());
                            if (!string.IsNullOrEmpty(processs[0].GetSafetyChar())) EchoSelectValue.Add(processs[0].GetSafetyChar());
                        }

                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            ProductSelectedValue = EchoSelectValue; // 作为按钮默认显示项
                            HoldActivitySectionModel.ProductSelectedValue = [.. EchoSelectValue];
                        });

                        if (EchoSelectValue.Count == 2)
                        {
                            await GetConfigInfos(EchoSelectValue[0], EchoSelectValue[1]); // 符合应用 + 有子项的情况，加载配置文件
                            if (EchoSelectValue[0].Contains("和易充"))
                            {
                                ActivityDetetor.SetMainAccording("HYC");
                            }
                            GetDBfieldMapInfos();
                        }
                    };

                    if (DatabaseSeriver.GetIdentify())
                    {
                        if (DatabaseSeriver.GetCloudDB() is not null and Supabase.Client CloudDB)
                        {
                            var queryResult = await CloudDB.From<ProductConfigRelation>().Get();
                            if (queryResult.Models.Count > 0)
                            {
                                List<object> products = [];
                                List<object> processs = [];

                                foreach (var model in queryResult.Models)
                                {
                                    LoaderData(model.PrdName, model.PrdProcess, model.PrdTreeKey, model.PrdApply);

                                    products.Add(model.PrdName); processs.Add(model.PrdProcess);
                                }

                                GetConfigInfo(products, processs);
                            }
                            else
                            {
                                ActivityEchoListItems = [];
                                ActivityListItems = [];
                            }
                        }
                    }
                    
                    else
                    {
                        string queryProductSql = $"SELECT * FROM product_config_relation";
                        if (await DatabaseSeriver.LocalDBQueryFree(queryProductSql) is var queryResult && queryResult != null)
                        {
                            if (queryResult.ErrorHint == null &&
                                queryResult.Result.TryGetValue(queryProductSql, out Dictionary<string, List<object>>? dataDict) &&
                                dataDict.TryGetValue("prd_id", out List<object>? ids) &&
                                dataDict.TryGetValue("prd_name", out List<object>? products) &&
                                dataDict.TryGetValue("prd_process", out List<object>? processs) &&
                                dataDict.TryGetValue("prd_treekey", out List<object>? childkeys) &&
                                dataDict.TryGetValue("prd_apply", out List<object>? applys) &&
                                products != null && processs != null)
                            {

                                for (int index = 0; index < products.Count; index++)
                                {
                                    string id = ids[index].GetSafetyChar();
                                    string product = products[index].GetSafetyChar();
                                    string process = processs[index].GetSafetyChar();
                                    int treekey = int.Parse(childkeys[index].GetSafetyChar());
                                    int apply = int.Parse(applys[index].GetSafetyChar());

                                    LoaderData(product, process, treekey, apply);
                                }
                                GetConfigInfo(products, processs);
                            }
                        }

                    }
                    
                    Dictionary<SelectorContentStruct, ObservableCollection<SelectorContentStruct>> NewPair = [];

                    //进行分类
                    foreach (var pair in pairClassify)
                    {
                        int selectItemsIndex = 0;
                        foreach (var _struct in ProductSelectItems)
                        {
                            if (_struct.Name == pair.Key)
                            {
                                _struct.Visibility = Visibility.Visible;
                                ProductSelectItems[selectItemsIndex] = _struct;

                                ObservableCollection<SelectorContentStruct> items = [];
                                foreach (var name in pair.Value)
                                {
                                    items.Add(new SelectorContentStruct("\ue691", name));
                                }
                                NewPair.TryAdd(_struct, items);
                                break;
                            }
                            selectItemsIndex++;
                        }
                    }
                    
                    ProductSelectItemPair = NewPair; //赋值子项
                    ProductSelectItemPair.TryAdd(ReserveDutyDB, ReserveDutyChilds);
                    propertyChangeSend(nameof(ProductSelectItemPair));
                    propertyChangeSend(nameof(ProductSelectedValue));
                });
                Logger.Debug($"product infos reset");
            }
            catch (Exception error)
            {
                Logger.Error($"product infos get error: {error.Message}");
            }
        }

        //获取数据库字段映射
        public async void GetDBfieldMapInfos(List<string>? columns = null)
        {
            try
            {
                HoldActivitySectionModel.DBWorkOrderMap.Clear();
                await Application.Current.Dispatcher.Invoke(async () =>
                {
                    string? product = ProductSelectedValue.GetSafetyChar<string>(0);
                    string? process = ProductSelectedValue.GetSafetyChar<string>(1);
                    if (!string.IsNullOrEmpty(product) &&
                        !string.IsNullOrEmpty(process))
                    {
                        if (DatabaseSeriver.GetIdentify())
                        {
                            if (DatabaseSeriver.GetCloudDB() is not null and Supabase.Client CloudDB)
                            {
                                // 查询映射
                                var queryResult = await CloudDB.From<DbFieldRelation>().Where(x => x.ProductName == product).Get();
                                if (queryResult.Models.Count > 0)
                                {
                                    DbFieldRelation? model = queryResult.Model;
                                    if (model is not null)
                                    {

                                        if (columns is not null && columns.Count > 0)
                                        {
                                            HoldActivitySectionModel.CusultColumnNames = columns;
                                        }
                                        else
                                        {
                                            HoldActivitySectionModel.CusultColumnNames = [.. Regex.Split(model.ConsultColumns, "\\s*&&\\s*")];
                                        }

                                        WorkOrderMapInfoStruct? relation = JsonSerializer.Deserialize<WorkOrderMapInfoStruct>(model.FieldJson,
                                            new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });

                                        if (relation is not null)
                                        {
                                            foreach (var field in relation.GetPropertys(1))
                                            {
                                                object? value = field.GetValue(relation);
                                                if (value is not null)
                                                {
                                                    HoldActivitySectionModel.DBWorkOrderMap.Add(field.Name, value.GetSafetyChar());
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (columns is not null && columns.Count > 0)
                                        {
                                            HoldActivitySectionModel.CusultColumnNames = columns;
                                            HoldActivitySectionModel.DBWorkOrderMap = [];
                                        }
                                    }
                                }
                                else
                                {
                                    if (columns is not null && columns.Count > 0)
                                    {
                                        HoldActivitySectionModel.CusultColumnNames = columns;
                                        HoldActivitySectionModel.DBWorkOrderMap = [];
                                    }
                                }
                            }
                        }
                        else
                        {
                            string queryConfigSql = $"SELECT consult_columns, field_json FROM dbfield_relation WHERE prd_name='{product}'";
                            if (await DatabaseSeriver.LocalDBQueryFree(queryConfigSql) is var queryResult)
                            {

                                if (queryResult.ErrorHint == null &&
                                    queryResult.Result.TryGetValue(queryConfigSql, out Dictionary<string, List<object>>? ConfigDict))
                                {

                                    if (ConfigDict is not null &&
                                        ConfigDict.TryGetValue("consult_columns", out List<object>? consult_columns) &&
                                        ConfigDict.TryGetValue("field_json", out List<object>? field_jsons))
                                    {
                                        if (consult_columns is not null)
                                        {
                                            if (columns is not null && columns.Count > 0)
                                            {
                                                HoldActivitySectionModel.CusultColumnNames = columns;
                                            }
                                            else
                                            {
                                                HoldActivitySectionModel.CusultColumnNames = [.. Regex.Split(consult_columns[0].GetSafetyChar(), "\\s*&&\\s*")];
                                            }

                                            WorkOrderMapInfoStruct? relation = JsonSerializer.Deserialize<WorkOrderMapInfoStruct>(field_jsons[0].GetSafetyChar());
                                            if (relation is not null)
                                            {
                                                foreach (var field in relation.GetPropertys(1))
                                                {
                                                    object? value = field.GetValue(relation);
                                                    if (value is not null)
                                                    {
                                                        HoldActivitySectionModel.DBWorkOrderMap.Add(field.Name, value.GetSafetyChar());
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (columns is not null && columns.Count > 0)
                                        {
                                            HoldActivitySectionModel.CusultColumnNames = columns;
                                            HoldActivitySectionModel.DBWorkOrderMap = [];
                                        }
                                    }
                                }
                                else
                                {
                                    if (columns is not null && columns.Count > 0)
                                    {
                                        HoldActivitySectionModel.CusultColumnNames = columns;
                                        HoldActivitySectionModel.DBWorkOrderMap = [];
                                    }
                                }
                            }
                        }
                    }

                    KeyValuePair<Dictionary<string, string>, List<string>> infoGrounp = new(HoldActivitySectionModel.DBWorkOrderMap,
                                                                                            HoldActivitySectionModel.CusultColumnNames);

                    WeakReferenceMessenger.Default.Send<MvvmMessage>(new MvvmMessage(MvvmMessage.MvvmType.Database_MapFilesSend, infoGrounp));

                    Logger.DebudElite($"dbfield map Infos load finish and map ui state: {ControlContent is ReserveDutyDBUI}");

                }, DispatcherPriority.Background);
            }
            catch (Exception error)
            {
                Logger.Error($"databasee map error: {error.Message}");
            }
        }

        //处理数据库映射数据
        public void EchoDBRelationDisposeEvent(object recipient, MvvmMessage message)
        {
            if (message.MsgBody is not null and Dictionary<string, string> translations)
            {
                string Jsonserial = JsonSerializer.Serialize<dynamic>(translations, new JsonSerializerOptions()
                {
                    WriteIndented = true
                });

                Thread Thread = new(async () =>
                {
                    string? product = HoldActivitySectionModel.ProductSelectedValue.GetSafetyChar(0);
                    if (!string.IsNullOrEmpty(product))
                    {
                        if (DatabaseSeriver.GetIdentify())
                        {
                            DbFieldRelation insertData = new()
                            {
                                ProductName = product,
                                FieldJson = Jsonserial,
                                ConsultColumns = HoldActivitySectionModel.CusultColumnNames.Join(" && ")
                            };

                            if (DatabaseSeriver.GetCloudDB() is not null and Supabase.Client CloudDB && product is not null)
                            {
                                var queryResult = await CloudDB.From<DbFieldRelation>().Where(x => x.ProductName == product).Get();

                                if (queryResult.Models is not null && queryResult.Models.Count > 0)
                                {
                                    await CloudDB.From<DbFieldRelation>()
                                    .Set(x => x.FieldJson, Jsonserial)
                                    .Where(x => x.ProductName == product)
                                    .Update();
                                    Logger.DebudElite("execute dbmap alter");
                                }
                                else
                                {
                                    await CloudDB.From<DbFieldRelation>().Insert(insertData);
                                    Logger.DebudElite("execute dbmap insert");
                                }

                                while (true)
                                {
                                    var verifyQuery = await CloudDB.From<DbFieldRelation>()
                                    .Where(x => x.ProductName == product)
                                    .Get();
                                    if (verifyQuery is not null && verifyQuery.Model is not null and DbFieldRelation data)
                                    {
                                        break;
                                    }
                                    await Task.Delay(2500);
                                }
                            }
                        }
                        else
                        {
                            string Sql = string.Empty;
                            var queryResult = await DatabaseSeriver.LocalDBQueryFree($"SELECT * FROM dbfield_relation WHERE prd_name='{product}'");
                            if (queryResult.Result.Count > 0)
                            {
                                Sql = $"UPDATE dbfield_relation SET " +
                                      $"consult_columns='{HoldActivitySectionModel.CusultColumnNames.Join(" && ")}'," +
                                      $"field_json ='{Jsonserial}' " +
                                      $"WHERE prd_name='{product}'";
                            }
                            else
                            {
                                Sql = $"INSERT INTO dbfield_relation VALUES(" +
                                      $"'{product}'," +
                                      $"'{Jsonserial}'," +
                                      $"'{3.GetDesorderly()}'," +
                                      $"'{HoldActivitySectionModel.CusultColumnNames.Join(" && ")}')";
                            }

                            await DatabaseSeriver.LocalDBQueryFree(Sql);
                        }

                        GetDBfieldMapInfos();
                    }

                    Logger.DebudElite($"dispose db relation, product: {product}");
                })
                {
                    IsBackground = true
                };

                Thread.Start();
            }
            return;
        }

        //处理配置返回数据
        public void EchoAttributeDisposeEvent(object recipient, MvvmMessage message)
        {
            string? product = HoldActivitySectionModel.ProductSelectedValue.GetSafetyChar(0);
            string? process = HoldActivitySectionModel.ProductSelectedValue.GetSafetyChar(1);

            if (message.MsgBody is not null and IEnumerable<MultilAtrributeStruct> Steps &&
                !string.IsNullOrEmpty(product) &&
                !string.IsNullOrEmpty(process))
            {
                ActivityBackEchoListItems = [.. ActivityEchoListItems];

                Thread Thread = new(async () =>
                {
                    string _Json = JsonSerializer.Serialize(Steps.ToList(), HoldActivitySectionModel.JsonOptions);

                    if (string.IsNullOrEmpty(_Json))
                    {
                        Logger.Information("config out infos JsonSerial fail");
                    }
                    else
                    {
                        Logger.Information($"save json for {product}-{process}");
                        if (DatabaseSeriver.GetIdentify())
                        {
                            if (DatabaseSeriver.GetCloudDB() is not null and Supabase.Client CloudDB)
                            {
                                string code = CryptoGraphic.ENbase64(product + process);
                                var existsQuery = await CloudDB.From<ProductConfigField>()
                                    .Where(x => x.Code == code)
                                    .Get();

                                if (existsQuery.ResponseMessage is not null && 
                                    existsQuery.ResponseMessage.IsSuccessStatusCode && 
                                    existsQuery.Model is not null && existsQuery.Models.Count == 1)
                                {
                                    var UpdateResponse = await CloudDB.From<ProductConfigField>()
                                           .Set(x => x.FieldJson, _Json)
                                           .Where(x => x.Code == code)
                                           .Update();

                                    DatabaseSeriver.CloudAnchorChannel<ProductConfigField>(async () =>
                                    {
                                        Logger.DebudElite("有响应");

                                        await Application.Current.Dispatcher.InvokeAsync(() =>
                                        {
                                        ProductRichBoxUI UI = new();
                                        ControlContent = UI;
                                        propertyChangeSend(nameof(DynamicRichContent));
                                        }, DispatcherPriority.Background);

                                        _ = GetConfigInfos(product, process);

                            });
                                }
                                else
                                {
                                    if (existsQuery.Models.Count == 0)
                                    {
                                        var InsertResponse = await CloudDB.From<ProductConfigField>()
                                        .Insert(new ProductConfigField()
                                        {
                                            Code = code,
                                            FieldJson = _Json,
                                            FieldProcess = process,
                                            FieldProduct = product
                                        });

                                    }
                                    else if (existsQuery.Models.Count > 1)
                                    {
                                        CustomMessageBox.Show("警告", 1, ["知道了"], $"存在{existsQuery.Models.Count}条数据");
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (DatabaseSeriver.LocalDBSurvival(DBreserveInfo.LocalDBName))
                            {
                                string queryConfigSql = $"SELECT * FROM product_config_field WHERE field_product='{product}' and field_process='{process}'";
                                if (await DatabaseSeriver.LocalDBQueryFree(queryConfigSql) is var queryResult)
                                {
                                    if (queryResult.ErrorHint == null &&
                                        queryResult.Result.TryGetValue(queryConfigSql, out Dictionary<string, List<object>>? ConfigDict))
                                    {
                                        if (ConfigDict is not null &&
                                            ConfigDict.TryGetValue("field_json", out List<object>? fieldJson))
                                        {
                                            if (fieldJson.Count == 0)
                                            {
                                                string insertCommandSql = $"INSERT INTO product_config_field VALUES(" +
                                                    $"'{_Json}'," +
                                                    $"'{product}'," +
                                                    $"'{process}')";
                                                await DatabaseSeriver.LocalDBQueryFree(insertCommandSql);
                                            }
                                            else if (fieldJson.Count > 1)
                                            {
                                                string insertCommandSql = $"UPDATE product_config_field SET field_json='{_Json}' WHERE " +
                                                      $"field_product='{product}'," +
                                                      $"field_process='{process}'";
                                                await DatabaseSeriver.LocalDBQueryFree(insertCommandSql);
                                                _ = GetConfigInfos(product, process);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                })
                {
                    IsBackground = true
                };
                Thread.Start();
            }
        }

        //数据库连接，用于切换数据库的执行方法
        public void DBconnectStart()
        {
            DBconnectWatch.Restart();
            DBTimer.Start();
        }
        
        // 初始化任务
        public async void ReadyWork(object? sender, EventArgs e)
        {
            var watch = Stopwatch.StartNew();
            if (DatabaseSeriver.GetIdentify())
            {
                if (DatabaseSeriver.GetCloudDB() is not null and Supabase.Client CloudDB)
                {
                    GetProductInfos();
                    DBTimer.Stop();
                }
            }
            else
            {
                if (DatabaseSeriver.LocalDBSurvival(DBreserveInfo.LocalDBName))
                {
                    DBTimer.Stop();

                    var parallelOptions = new ParallelOptions
                    {
                        MaxDegreeOfParallelism = 3
                    };

                    List<Action> Tasks = [TableCreate, GetProductInfos];
                    await Task.Run(() =>
                    {
                        Parallel.ForEachAsync(Tasks, parallelOptions, (task, cancellationToken) =>
                        {
                            task();
                            return ValueTask.CompletedTask;
                        });
                    });
                }
            }
            if (DBconnectWatch.ElapsedMilliseconds > DBconnectTimeOut)
            {
                DBconnectWatch.Restart();
                DBconnectWatch.Stop();
                DBTimer.Stop();
                Logger.DebudElite("activity ready task timeout");
            }
        }

        //表创建
        public async void TableCreate()
        {
            await Task.Run(async () =>
            {

                string verityTableSql = "select name from sqlite_master where type='table'";

                var sqltablecreate = await DatabaseSeriver.LocalDBQueryFree(verityTableSql);

                List<string> unexistsTables = [];

                foreach (var key in HoldActivitySectionModel.TableReserveDuty.Keys)
                {
                    if (sqltablecreate.ErrorHint == null && sqltablecreate.Result.TryGetValue(verityTableSql, out var keyValues))
                    {
                        if (keyValues.TryGetValue("name", out List<object>? tables) && tables is not null)
                        {
                            if (!tables.Contains(key)) unexistsTables.Add(HoldActivitySectionModel.TableReserveDuty[key]);
                        }
                        else
                        {
                            unexistsTables.Add(HoldActivitySectionModel.TableReserveDuty[key]);
                        }
                    }
                    else
                    {
                        unexistsTables.Add(HoldActivitySectionModel.TableReserveDuty[key]);
                    }
                }
                if (await DatabaseSeriver.LocalDBQuery(unexistsTables) is SqliteExceuteResult result &&
                    result.ErrorHint == null)
                {
                    Logger.Debug("dispose sql of table create");
                }
                else
                {
                    Logger.Error("table create fail");
                }
            }).ConfigureAwait(false);
        }

        public void SerialDataReceive(string receive)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                ActivityDetetor.Run(receive);
            });
        }

        public void ReturnReceipt(Check Message)
        {
            MessageProPlantType Type = Message.Type;
            int index = Message.Row;
            object? message = Message.Message;
            bool isQuestion = Message.AssertQuestion;

            Application.Current.Dispatcher.InvokeAsync(async () =>
            {

                if (Type.HasFlag(MessageProPlantType.Success))
                {
                    if (ActivityListItems.Count > index)
                    {
                        ActivityListItems[index] = new ActivityListBoxItemStruct(ActivityListItems[index].ActivityName, "JadeFlow".FindSolidBrush());
                    }
                }


                if (Type.HasFlag(MessageProPlantType.Failed))
                {
                    if (ActivityListItems.Count > index)
                    {
                        ActivityListItems[index] = new ActivityListBoxItemStruct(ActivityListItems[index].ActivityName, "SunsetCoral".FindSolidBrush());
                        if (HoldActivitySectionModel.ProductSelectedValue.Count == 2)
                        {
                            CustomMessageBox.Show($"{HoldActivitySectionModel.ProductSelectedValue[0]} - {HoldActivitySectionModel.ProductSelectedValue[1]}",
                                                  $"{HoldActivitySectionModel.ProductSelectedValue[1]}测试不通过", false);
                        }
                    }
                }


                if (Type.HasFlag(MessageProPlantType.Question))
                {
                    if (message is not null && message is CustomMessageBox.Field FieldMessage)
                    {
                        if (FieldMessage.itemsSource.Count > 0)
                        {
                            CustomMessageBox.Invoke Invoke = CustomMessageBox.Show(FieldMessage.title, FieldMessage.options, FieldMessage.itemsSource);
                            ActivityDetetor.SendQuestioning(Invoke);
                        }
                        else
                        {
                            CustomMessageBox.Invoke Invoke = CustomMessageBox.Show(FieldMessage.title, FieldMessage.type, FieldMessage.options, FieldMessage.message);
                            ActivityDetetor.SendQuestioning(Invoke);
                        }
                    }
                }


                if (Type.HasFlag(MessageProPlantType.Message))
                {
                    if (message is not null)
                    {
                        DynamicRichContent.Add(message.GetSafetyChar() + "\n\n");
                    }
                }


                if (Type.HasFlag(MessageProPlantType.MacUpdate))
                {
                    if (message is not null and List<string> macInvoke && macInvoke.Count == 2)
                    {
                        if (DatabaseSeriver.GetIdentify())
                        {
                            if (DatabaseSeriver.GetCloudDB() is not null and Supabase.Client CloudDB)
                            {
                                //CloudDB.From<WorkOrderUnfold>().Set(x=>"blue_mac", macInvoke.First()).Where(x=>x.Imei == macInvoke.Last()).Update();
                            }
                        }
                        else
                        {
                            if (DatabaseSeriver.LocalDBSurvival(DBreserveInfo.LocalDBName))
                            {
                                await DatabaseSeriver.LocalDBQueryFree($"UPDATE workorder_unfold SET blue_mac='{macInvoke.First()}' WHERE imei='{macInvoke.Last()}'");
                            }
                        }
                    }
                }


                if (Type.HasFlag(MessageProPlantType.PushFinish))
                {                    
                    if (HoldActivitySectionModel.ProductSelectedValue.Count == 2)
                    {
                        Logger.DebudElite("产测完成了", HoldActivitySectionModel.ProductSelectedValue.Count);
                        CustomMessageBox.Show($"{HoldActivitySectionModel.ProductSelectedValue[0]} - {HoldActivitySectionModel.ProductSelectedValue[1]}",
                                              $"{HoldActivitySectionModel.ProductSelectedValue[1]}测试通过", true);
                    }
                }


                if (Type.HasFlag(MessageProPlantType.HeartBeats))
                {
                    if (message is not null)
                    {
                        RunningStartContent = message.GetSafetyChar();
                    }
                }


                if (Type.HasFlag(MessageProPlantType.Initialize))
                {
                    await Task.Run(() =>
                    {
                        RecoverEctivityListItem();
                    });
                }


                if (Type.HasFlag(MessageProPlantType.DimProcess))
                {
                    if (message is not null and KeyValuePair<double, string> _process)
                    {
                        if (HoldActivitySectionModel.DimProcess is null) HoldActivitySectionModel.DimProcess = CustomMessageBox.Show(0, 10, 300);

                        if (_process.Key == 10.0)
                        {
                            HoldActivitySectionModel.DimProcess.Invoke(_process.Key, _process.Value);
                            HoldActivitySectionModel.DimProcess = null;
                        }
                        else
                        {
                            HoldActivitySectionModel.DimProcess.Invoke(_process.Key, _process.Value);
                        }
                    }

                    await Task.Run(() =>
                    {
                        RecoverEctivityListItem();
                    });
                }
            });
        }

        public async void OpenorConfigArgEvent(object? param)
        {
            var ArgSearchConfig = await CustomMessageBox.Show("参数设置", ["取消", "确定"], HoldActivitySectionModel.ArgReturnReceiptMap);

            if (ArgSearchConfig.Item1 == 1 && ArgSearchConfig.Item2 is not null)
            {
                HoldActivitySectionModel.ArgReturnReceiptMap = ArgSearchConfig.Item2;

                string? IMEI = null;
                string? SN = null;
                string? DOID = null;
                string? BLUE = null;
                string? QRCODE_1 = null;
                string? QRCODE_2 = null;

                foreach (var _behivor in ActivityAssistBehivor.Behivor.ParamReserveDutyMap)
                {
                    if (ArgSearchConfig.Item2.TryGetValue(_behivor.Key, out string? _value))
                    {
                        switch (_behivor.Key)
                        {
                            case "IMEI":
                                IMEI = _value;
                                break;
                            case "SN":
                                SN = _value;
                                break;
                            case "DOID":
                                DOID = _value;
                                break;
                            case "BLUE":
                                BLUE = _value;
                                break;
                            case "QRCODE_1":
                                QRCODE_1 = _value;
                                break;
                            case "QRCODE_2":
                                QRCODE_2 = _value;
                                break;
                        }
                    }
                }
                if (IMEI != null &&
                    SN != null &&
                    BLUE != null &&
                    DOID != null)
                {
                    ActivityDetetor.SetMainAccording(IMEI, SN, BLUE, DOID, QRCODE_1, QRCODE_2);
                }
            }
        }
    }
}
